/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.meta.service.table.impl;

import com.alibaba.fastjson2.JSON;
import com.google.common.base.Strings;
import com.je.common.base.DynaBean;
import com.je.meta.model.database.type.ImportedKeyCascadeTypeEnum;
import com.je.meta.model.database.type.ImportedKeyTypeEnum;
import com.je.meta.service.table.AbstractTableTrace;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("tableKeyTrace")
public class TableKeyTraceImpl extends AbstractTableTrace {

    @Override
    public DynaBean save(List<DynaBean> columns, DynaBean trace, DynaBean oldBean, DynaBean newBean, String oper) {
        if ("INSERT".equals(oper)) {
            return null;
        }
        List<Map<String, Object>> dataList = new ArrayList<Map<String, Object>>();
        if ("UPDATE".equals(oper)) {
            trace.set("TABLETRACE_OPER", "修改");
            if (oldBean != null && Strings.isNullOrEmpty(oldBean.getStr("TABLEKEY_COLUMNCODE"))) {
                trace.set("TABLETRACE_OPER", "添加");
                oper = "INSERT";
            }
            for (DynaBean column : columns) {
                if (column.getStr("TABLECOLUMN_CODE").startsWith("SY_")) {
                    continue;
                }
                Map<String, Object> map = buildJsonData(oper, column, newBean, oldBean);
                if (map != null) {
                    dataList.add(map);
                }
            }
            if (dataList.size() == 0) {
                return trace;
            }
        } else if ("DELETE".equals(oper)) {
            if (oldBean == null) {
                oldBean = newBean;
            }
            trace.set("TABLETRACE_OPER", "删除");
            for (DynaBean column : columns) {
                if (column.getStr("TABLECOLUMN_CODE").startsWith("SY_")) {
                    continue;
                }
                Map<String, Object> map = buildJsonData(oper, column, newBean, oldBean);
                dataList.add(map);
            }
        }
        String jsonStr = "";
        if (dataList.size() > 0) {
            jsonStr = JSON.toJSONString(dataList);

        }
        String tableColumnCode = oldBean.getStr("TABLEKEY_COLUMNCODE");
        if (Strings.isNullOrEmpty(tableColumnCode)) {
            tableColumnCode = newBean.getStr("TABLEKEY_COLUMNCODE");
        }
        if (!Strings.isNullOrEmpty(newBean.getStr("TABLEKEY_ISCREATE")) && newBean.getStr("TABLEKEY_ISCREATE").equals("1")) {
            trace.set("TABLETRACE_SFYY", "1");
        } else {
            trace.set("TABLETRACE_SFYY", "0");
        }
        trace.set("TABLETRACE_FIELDNAME", tableColumnCode);
        trace.set("TABLETRACE_FIELDTYPE", getKeyTypeNameByTypeCode(newBean.getStr("TABLEKEY_TYPE","")));
        trace.set("TABLETRACE_TABLENAME", "表格键");
        trace.set("TABLETRACE_FIELDCODE", newBean.getStr("TABLEKEY_CODE"));
        trace.set("TABLETRACE_XGNRJSON", jsonStr);
        metaService.insert(trace);
        return trace;
    }

    private String getKeyTypeNameByTypeCode(String type) {
        if (type.equals(ImportedKeyTypeEnum.Inline.toString())) {
            return "内联外键";
        } else if (type.equals(ImportedKeyTypeEnum.Foreign.toString())) {
            return "外键";
        } else if (type.equals(ImportedKeyTypeEnum.Primary.toString())) {
            return "主键";
        }
        return "";
    }

    private Map<String, Object> buildJsonData(String oper, DynaBean column, DynaBean newBean, DynaBean oldBean) {
        Map<String, Object> map = new HashMap<>();
        String columnCode = column.getStr("TABLECOLUMN_CODE");
        if (!"INSERT".equals(oper)) {
            if (!"DELETE".equals(oper) && (newBean.getStr(columnCode, "").equals(oldBean.getStr(columnCode, "")))) {
                return null;
            }
        }
        map.put("tableColumnName", column.getStr("TABLECOLUMN_NAME"));
        map.put("tableColumnCode", column.getStr("TABLECOLUMN_CODE"));
        String code = column.getStr("TABLECOLUMN_CODE");
        if ("INSERT".equals(oper)) {
            map.put("type", "insert");
            map.put("tableColumnValue", getValueByCode(code, newBean.getStr(code, "")));
        }
        if ("UPDATE".equals(oper)) {
            map.put("type", "update");
            map.put("tableColumnOldValue", getValueByCode(code, oldBean.getStr(code, "")));
            map.put("tableColumnValue", getValueByCode(code, newBean.getStr(code, "")));
        }
        if ("DELETE".equals(oper)) {
            map.put("type", "delete");
            map.put("tableColumnValue", getValueByCode(code, newBean.getStr(code, "")));
        }
        return map;
    }


    public String getValueByCode(String code, String value) {
        if (code.equals("TABLEKEY_ISCREATE")) {
            if (value.equals("1")) {
                return "是";
            } else {
                return "否";
            }
        }

        if (code.equals("TABLEKEY_CHECKED")) {
            if (value.equals("1")) {
                return "是";
            } else {
                return "否";
            }
        }

        if (code.equals("TABLEKEY_ISRESTRAINT")) {
            if (value.equals("1")) {
                return "是";
            } else {
                return "否";
            }
        }

        if (code.equals("TABLEKEY_LINETYLE") && value.equals(ImportedKeyCascadeTypeEnum.CASCADE.getValue())) {
            return "级联";
        } else if (code.equals("TABLEKEY_LINETYLE") && value.equals(ImportedKeyCascadeTypeEnum.SETNULL.getValue())) {
            return "设置空";
        } else if (code.equals("TABLEKEY_LINETYLE") && value.equals(ImportedKeyCascadeTypeEnum.NOACTION.getValue())) {
            return "不做处理";
        }

        if (code.equals("TABLEKEY_TYPE")) {
            return getKeyTypeNameByTypeCode(code);
        }
        return value;
    }


}
